<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>yield*语句</title>
</head>
<body>
    <h1>yield*语句</h1>

    <script>
        // yield*语句用于异步遍历器的嵌套
        async function* gen1() {
            yield 'a';
            yield 'b';
            return 2;
        }

        async function* gen2() {
            const result = yield* gen1();
            console.log(result); // 2
            yield 'c';
        }

        // 使用for await...of遍历
        async function test() {
            for await (const x of gen2()) {
                console.log(x); // 'a', 'b', 'c'
            }
        }

        // 实际应用：异步数据流的组合
        async function* readFiles(files) {
            for (const file of files) {
                yield await readFile(file);
            }
        }

        async function* processFiles(files) {
            yield* readFiles(files);
        }

        // 模拟文件读取
        function readFile(file) {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(`文件 ${file} 的内容`);
                }, 1000);
            });
        }

        // 使用示例：处理多个数据源
        async function* combineStreams(stream1, stream2) {
            yield* stream1;
            yield* stream2;
        }

        // 创建异步数据流
        async function* createStream(prefix, count) {
            for (let i = 0; i < count; i++) {
                await new Promise(resolve => setTimeout(resolve, 1000));
                yield `${prefix}-${i}`;
            }
        }

        // 使用组合流
        async function useStreams() {
            const stream1 = createStream('A', 3);
            const stream2 = createStream('B', 2);
            const combinedStream = combineStreams(stream1, stream2);

            for await (const value of combinedStream) {
                console.log(value);
                // 输出：
                // A-0
                // A-1
                // A-2
                // B-0
                // B-1
            }
        }

        useStreams();
    </script>
</body>
</html> 